/*
 * @Author: Wilbur
 * @Date: 2018-11-17 16:37:43
 * @Last Modified by: Wilbur
 * @Last Modified time: 2019-06-04 13:46:17
 */
<template>
    <div class="container task-list-container">
        <div class="operation-wrapper">
            <el-button
                type="primary"
                @click="handleRoute('StudentTaskAdd')"
                :disabled="!authResult.auth_add"
                size="small">添加任务</el-button>
        </div>
        <div class="content-wrapper">
            <el-row
                class="search-wrapper"
                :gutter="20">
                <el-form
                    label-position="left"
                    label-width="84px"
                    size="small">
                    <el-col
                        class="filter-item"
                        :span="24">
                        <el-form-item label="任务名称：">
                            <!-- <el-autocomplete
                                class="inline-input"
                                v-model="filterData.title"
                                value-key="title"
                                :fetch-suggestions="querySearchByTitle"
                                @select="getTableData"
                                clearable
                                @change="fnTest"
                                placeholder="请输入并选择任务名称" />
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="getTableData">搜索
                                    </el-button> -->
                            <el-select
                                v-model="filterData.title"
                                filterable
                                clearable
                                @change="getTableData"
                                placeholder="请选择">
                                <el-option
                                    v-for="item in taskTitleList"
                                    :key="item.task_no"
                                    :label="item.title"
                                    :value="item.title"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="table-wrapper">
                <el-table
                    :data="tableData"
                    height="100%"
                    @sort-change="handleSortChanged"
                    style="width: 100%;">
                    <el-table-column
                        fixed="left"
                        header-align="left"
                        align="center"
                        :width="50"
                        label="序号">
                        <template slot-scope="scope">
                            <div class="table-index">
                                {{ scope.$index + 1 }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="left"
                        prop="title"
                        width="250"
                        show-overflow-tooltip
                        label="任务名称"/>
                    <!-- <el-table-column
                        prop="type"
                        min-width="80"
                        label="任务类别">
                        <template slot-scope="scope">
                            {{ scope.row.type == 1 ? '成长任务' : '普通任务' }}
                        </template>
                    </el-table-column> -->
                    <el-table-column
                        :formatter="emptyFormatter"
                        prop="all_count"
                        min-width="104"
                        show-overflow-tooltip
                        sortable="custom"
                        label="任务总数"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.accept_count+ '/' +scope.row.all_count }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="award"
                        min-width="104"
                        show-overflow-tooltip
                        sortable="custom"
                        label="任务奖励">
                        <template slot-scope="scope">
                            <template v-if="scope.row.award_money">{{ scope.row.award_money }}元</template>
                            <template v-else-if="scope.row.award_score">{{ scope.row.award_score }}积分</template>
                            <template v-else>--</template>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="has_statistic_config"
                        :formatter="BooleanFormatter"
                        label="反馈统计" />
                    <el-table-column
                        prop="sort"
                        sortable="custom"
                        label="排序">
                        <template slot-scope="scope">
                            <span>{{ scope.row.sort }}</span>
                            &nbsp;&nbsp;|&nbsp;&nbsp;
                            <i
                                class="iconfont icon-bianji"
                                @click="fnEditSort(scope.row.task_no)"/>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="read_count"
                        label="浏览量"
                        show-overflow-tooltip
                        sortable='custom'
                    />
                    <el-table-column
                        prop="submit_config"
                        min-width="100"
                        label="反馈要求">
                        <template slot-scope="scope">
                            <div
                                v-if="scope.row.submit_config.need_text_count > 0 || scope.row.submit_config.need_image_item_count > 0"
                                style="font-size: 0;white-space: nowrap;">
                                <span
                                    class="submit-config-item"
                                    v-if="scope.row.submit_config.need_text_count">
                                    <span class="num">{{ scope.row.submit_config.need_text_count }}</span>
                                    <i class="iconfont icon-chunwenbentag" />
                                </span>
                                <span
                                    class="submit-config-item"
                                    v-if="scope.row.submit_config.need_image_item_count">
                                    <span class="num">{{ scope.row.submit_config.need_image_item_count }}</span>
                                    <i class="iconfont icon-tupian" />
                                </span>
                            </div>
                            <template v-else>--</template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="status"
                        label="是否上架">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                inactive-color="rgba(0, 0, 0, .25)"
                                :active-value="1"
                                :inactive-value="0"
                                @change="handleSetTaskStatus($event, scope.row.task_no)" />
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="time"
                        min-width="160"
                        label="任务时间">
                        <template slot-scope="scope">
                            {{ scope.row.start_time*1000 | dateFormatter('yyyy/MM/dd HH:mm') }}至<br>
                            {{ scope.row.end_time*1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="date"
                        label="操作"
                        fixed="right"
                        :width="260">
                        <template slot-scope="scope">
                            <div>
                                <!-- <div>
                                    <el-popover
                                        placement="top"
                                        width="200"
                                        popper-class="task-list-preview-popover"
                                        trigger="click">
                                        <el-button
                                            slot="reference"
                                            type="text">预览</el-button>
                                        <img
                                            :src="`${baseUrl}/__local/common%5Cqrcode?content=${escape(mobileUrl + '/task-detail?id=' + scope.row.task_no)}&__ticket=${sessionTicket}`"
                                            alt=""
                                            width="104px"
                                            height="104px">
                                    </el-popover>
                                </div> -->


                                <div>
                                    <el-button
                                        type="text"
                                        :disabled="!authResult.auth_edit"
                                        @click="handleRoute('StudentTaskEdit', { task_no: scope.row.task_no })">编辑</el-button>
                                    <el-button
                                        type="text"
                                        :disabled="!authResult.auth_audit"
                                        @click="handleRoute('StudentTaskReviewList', { task_no: scope.row.task_no, one_task: 1 })">反馈统计</el-button>
                                    <!-- <el-button
                                        type="text"
                                        style="margin-left:10px;"
                                        @click="fnShowTaskLink(scope.row.task_no)">链接</el-button> -->
                                    <el-button
                                        type="text"
                                        :disabled="!authResult.auth_delete"
                                        @click="handleDeleteTask(scope.row.task_no)"
                                        class="btn-delete">删除</el-button>
                                    <el-button
                                        type="text"
                                        v-if="scope.row.status == 1"
                                        @click="fnRecommend(scope.row.task_no)"
                                    >推荐到首页</el-button>

                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData" />
            </div>
        </div>
        <el-dialog
            title="复制链接"
            :visible.sync="dialogLinkVisible"
            width="30%"
            @close="targetLink = ''">
            <div class="dialog-link"><span class="link-label">原链接:</span><span
                class="link-value"
                @click="fnChooseText('link')"
                ref="link">{{ targetLink }}</span></div>
            <div class="dialog-link"><span class="link-label">短链接:</span><span
                class="short-link-value"
                @click="fnChooseText('shortLink')"
                ref="shortLink">{{ shortLink }}</span></div>

            <span
                slot="footer"
                class="dialog-footer">
                <!-- <el-button
                    size="small"
                    @click="dialogLinkVisible = false">取消</el-button>
                <el-button
                    class="btn-copy"
                    data-clipboard-target="#link"
                    size="small"
                    type="primary">复制</el-button> -->
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Clipboard from 'clipboard';

let sortFieldMap = {
    all_count: 1,
    award: 2,
    read_count: 3,
    sort: 4
};
let sortTypeMap = {
    'ascending': 1,
    'descending': 0
};

export default {
    data() {
        return {
            authResult: {},
            taskTitleList: [],
            tableData: [],
            filterData: {
                title: ''
            },
            sortData: {
                field: 0,
                by: 1
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            targetLink: '',//链接
            shortLink: '', //短链接
            dialogLinkVisible: false,
            baseUrl: '',
            mobileUrl: '',
            escape: escape,
            sessionTicket: localStorage.getItem('sessionTicket')
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.baseUrl = this.$baseUrl;
        this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
        this.$store.commit('SET_HEADER', [
            {
                title: "工作",
            },
            {
                title: '任务管理'
            },
            {
                title: "任务列表"
            }
        ]);
        this.getTableData();
        this.getTasks();
    },
    mounted() {
        this.handleInitCopy();
    },
    methods: {
        fnEditSort(task_no) {
            this.$prompt('数字越小，排序越靠前', '排序', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                center: true,
                customClass: 'sort-dialog',
                inputPattern: /^\d{1,5}$/,
                inputErrorMessage: '请输入正确的排序序号'
            }).then(({ value }) => {
                this.$post('/student/task%5Cset_sort', {
                    task_no: task_no,
                    sort: parseInt(value)
                }, resp => {
                    if(resp.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '操作成功'
                        });
                        this.getTableData();
                    }else{
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            }).catch(() => {
                console.log('cancel');
            });
        },
        fnTest() {
            console.log('===');
        },
        fnShowTaskLink(taskNo){
            this.targetLink = `${this.mobileUrl}/task-detail?id=${taskNo}`;
            this.$post('/__local/common%5Cshort_url', {
                url: this.targetLink
            }, resp => {
                if(resp.code == 1){
                    this.shortLink = resp.data.short_url;
                }else{
                    this.shortLink = '--';
                }
                this.dialogLinkVisible = true;
            });
        },
        fnChooseText(name){
            let text = this.$refs[name];
            let range = '';

            if (document.body.createTextRange) {
                range = document.body.createTextRange();

                range.moveToElementText(text);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();

                range = document.createRange();

                range.selectNodeContents(text);
                selection.removeAllRanges();
                selection.addRange(range);

            } else {
                alert("none");
            }
        },
        /**
         * 获取任务名称列表
         */
        getTasks() {
            this.$post('/student/task%5Csuggest', {
                query: ''
            }, resp => {
                if (resp.code == 1) {
                    this.taskTitleList = resp.data.list;
                }
            });
        },
        /**
         * 获取表格数据
         */
        getTableData(page) {
            this.$post('/student/task%5Cget_list', {
                page_id: page || this.page.now_page,
                title: this.filterData.title,
                sort_field: this.sortData.field,
                sort_type: this.sortData.by
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 跳转页面
         */
        handleRoute(name, query) {
            let obj = {
                name
            };

            if (query) {
                obj.query = query;
            }

            this.$router.push(obj);
        },

        /**
         * 筛选符合输入的人物名称
         */
        querySearchByTitle(queryString, cb) {
            let tasks = this.taskTitleList;
            // let results = queryString ? tasks.filter(this.createFilter(queryString)) : tasks;

            // 调用 callback 返回建议列表的数据
            console.log(tasks);
            cb(tasks);
        },
        /**
         * 排序
         */
        handleSortChanged(data) {
            if (data.order) {
                console.log(data);
                this.sortData.field = sortFieldMap[data.prop];
                this.sortData.by = sortTypeMap[data.order];
            } else {
                this.sortData.field = 0;
                this.sortData.by = 1;
            }

            this.getTableData();
        },

        /**
         * 复制链接
         */
        handleInitCopy() {
            let clipboard = new Clipboard('.btn-copy');

            clipboard.on('success', e => {
                this.dialogLinkVisible = false;
                this.$message({
                    type: 'success',
                    message: '复制成功'
                });
                e.clearSelection();
            });

            clipboard.on('error', e => {
                this.$message({
                    type: 'warning',
                    message: '未复制成功，请手动复制'
                });
            });
        },

        /**
         * 删除任务
         */
        handleDeleteTask(id) {
            this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/task%5Cdelete', {
                    task_no: id
                }, resp => {
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '删除成功'
                        });
                    } else {
                        this.$message({
                            type: 'warning',
                            message: resp.msg || '删除失败'
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 任务名称筛选辅助函数
         */
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.title.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
            };
        },

        /**
         * 列表渲染辅助函数：列表项为空处理
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },

        /**
         * 列表渲染辅助函数：列表项为是否
         */
        BooleanFormatter(row, column, val) {
            if (val == 1) {
                return '是';
            } else if (val == 0) {
                return '否';
            }

            return val;
        },

        /**
         * 设置任务状态
         */
        handleSetTaskStatus(status, id) {

            this.$post('/student/task%5Cset_status', {
                task_no: id,
                status,
                need_send_message: 0
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg ||'设置失败'
                    });
                    this.getTableData();
                }
            });
        },

        /**
         * 推荐到首页
         */
        fnRecommend (id) {
            this.$confirm('确认后推送该项目至【首页推荐】页面', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/work_recommend%5Cadd', {
                    type: 3,
                    aim_no: id
                }, resp => {
                    if (resp.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '推荐成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            }).catch(() => {
            });
        }
    }
};
</script>

<style lang="less" scoped>
.container {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.operation-wrapper {
    display: flex;
    flex-direction: row-reverse;
    padding: 12px 23px;
    background-color: #fff;

    .el-button {
        margin-left: 10px;
    }
}
.content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 15px;
    overflow: hidden;
}
.search-wrapper {
    padding: 15px;
    background-color: #fff;
}
.filter-item {
    .el-form-item {
        margin-bottom: 0;
        white-space: nowrap;
    }
    .el-input {
        width: auto;
        vertical-align: middle;
    }
    .el-button {
        margin-left: 15px;
        vertical-align: middle;
    }
}
.table-wrapper {
    flex: 1;
    background-color: #fff;

    .el-button {
        padding: 0;
    }
    .icon-bianji{
        font-size: 14px;
        color: #B9B9B9;
        cursor: pointer;
    }
    .btn-delete {
        color: #fd4d32;
        &.is-disabled {
            color: #c0c4cc;
            cursor: not-allowed;
        }
    }
    .submit-config-item {
        display: inline-block;
        position: relative;
        padding-right: 10px;
        font-size: 14px;

        & + .submit-config-item {
            padding-left: 10px;
            &::before {
                content: '';
                position: absolute;
                top: 50%;
                left: 0;
                width: 1px;
                height: 14px;
                transform: translate(0, -50%);
                background-color: #d8d8d8;
            }
        }

        .num {
            vertical-align: middle;
        }
        .iconfont {
            font-size: 16px;
            color: #b9b9b9;
            vertical-align: middle;
        }

        .icon-tupian {
            font-size: 20px;
        }
    }
}
.pagination-wrapper {
    padding-top: 10px;
    .el-pagination {
        float: right;
        padding: 0;
        background-color: transparent;
    }
}
.dialog-link{
    & + .dialog-link{
        margin-top: 20px;
    }
    .link-label{
        font-weight: 500;
        margin-right: 20px;
    }
    .link-value{
    }
}
</style>
<style lang="less">
.task-list-container {
    tbody {
        .cell {
            display: flex;
            align-items: center;
            height: 48px;
        }
    }
}
.task-list-preview-popover {
    min-width: auto!important;
    width: 120px!important;
    height: 120px;
    padding: 8px!important;
}
.sort-dialog{
    width: 270px!important;
}
</style>
